
#include "can-ctrl.h"

#include "common_text.h"
const char txt_start[19] = "======START=======";
const char txt_separator_line[11] = "==========";

uint32_t testbyte;
uint8_t i;




void masterInit(void)
{
	sei();
	timer_init();
	usart_init();
	usart_writeln("");
	usart_writeln(txt_start);
	spi_init();
	mcp2515_init();
	lcd_init();
	_delay_ms(20);
	module_io_init();
	module_program_init();
	
	register_slot(main_escape_to_menu, btn_event);
	
	#ifdef DEBUG
	usart_writeln("masterinit...READY");
    lcd_splash_screen();
	#endif
}

int main(void)
{
	i=0;
    int16_t temperature;
    /* Initialise all */
    masterInit();
	
	#ifdef DEBUG
	
	#ifdef UNITTEST
	//run_unittest();
	#endif
	
	//lcd_write_charset();

	lcd_clear_display();
	lcd_clear_command_line();
	
	lcd_refresh();

	lcd_refresh();
	
	add_prog(&prog_menu);
	add_prog(&prog_usartmenu);
	progs_running();
	slots_registered();
	#endif
	#ifdef DEBUG
	usart_writeln("Begin main loop");
	#endif


	uint8_t status = 0;	
    
	while(1)
	{
		module_io_run();
 		usart_run();

		module_program_run();
		
        //Exit to mainmenu if joy_left held for 4sec
        if(buttonheld(joy_left, 4000) && !prog_is_running(&prog_menu))
		{
			sound(6000, 100);
			remove_lcdwriting_progs();
			add_prog(&prog_menu);
			
		}
    }
}

void main_escape_to_menu(Event *event)
{
	Button *button = (Button *) event->data;
	uint16_t *time = (uint16_t *) event->data+1;
// 	if(*button == joy_left && *time > 4000 && !prog_is_running(&prog_menu))
// 	{
// 		
// 	}
	if(*button == joy_right && *time > 1000)
	{
		progs_running();
		slots_registered();
	}
	
}

#ifdef UNITTEST
void run_unittest(void)
{
	#ifdef MODULE_IO_UNITTEST
	module_io_unittest();
	#endif

}
#endif
